<?php
/**
 * Created by PhpStorm.
 * User: 76683
 * Date: 2018/7/17
 * Time: 21:22
 */

namespace app\api\model;


use think\Model;

class WeCategory extends Model
{
    protected $autoWriteTimestamp = true;

    /**
     * @param $keywords
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\exception\DbException
     */
    public function search($keywords)
    {
        $model = new self();
        $data_list = $model->alias('c')
            ->join('__WE_TOPIC__ t', 'c.id = t.category_id and t.status = 1 and t.is_delete = 0', 'left')
            ->join('__WE_TOPIC_DETAIL__ td', 't.id = td.topic_id and td.status = 1 and td.is_delete = 0', 'left')
            ->field('c.id,c.name,ifnull((sum(t.likes)+ sum(td.likes)),0) as t_likes, sum(t.details) as t_details')
            ->where(['c.name' => ['like', '%' . $keywords . '%'], 'c.status' => 1, 'c.is_verify' => 1, 'c.is_delete' => 0])
            ->group('c.id')
            ->order('t_likes desc,t_details desc')
            ->paginate(config('sd_config.list_len'));
        return empty($data_list) ? [] : $data_list->toArray();
    }

    /**
     * @param $data
     * @return array
     * @throws \think\Exception
     */
    public function applyCate($data)
    {
        $saveData = [
            'name' => $data['name'],
            'status' => 1,
            'is_verify' => 0,
        ];
        return self::create($saveData)->toArray();
    }

    /**
     * 热门领域
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\exception\DbException
     */
    public function hot()
    {
        $pubCate = self::pubCate();
        $model = new self();
        $data_list = $model->alias('c')
            ->join('__WE_TOPIC__ t', 'c.id = t.category_id', 'left')
            ->where(['t.status' => 1, 't.is_delete' => 0, 'c.is_verify' => 1, 'c.is_delete' => 0, 'c.id' => ['<>', $pubCate]])
            ->field('distinct(c.id),c.`name`,sum(case t.id when t.id then 1 else 0 end) as num')
            ->group('c.id')
            ->orderRaw('sum(case t.id when t.id then 1 else 0 end) desc')
            ->paginate(5)
            ->toArray();
        return empty($data_list['data']) ? [] : $data_list;
    }

    public static function pubCate($flag = false)
    {
        $data = self::where(['name' => '公共树洞'])->field('id,name')->find();
        if (empty($data)) {
            return [];
        } else {
            $data = $data->toArray();
        }
        return $flag ? $data : $data['id'];
    }
}